package com.nuanshui.heatedloan.config;

import com.nuanshui.framework.res.ResourceFacade;
import com.nuanshui.framework.springContext.SpringPropertiesUtil;
import com.nuanshui.heatedloan.extension.PayBizTypeEnumArgumentResolver;
import com.nuanshui.heatedloan.extension.SetMethodProcessor;
import com.nuanshui.heatedloan.extension.interceptor.LogUtilInterceptor;
import com.nuanshui.heatedloan.extension.interceptor.OrganizationInterceptor;
import com.nuanshui.heatedloan.extension.pageable.CustomPageableHandlerMethodArgumentResolver;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
 * spring mvc 设置
 * @ClassName: WebMvcConfig 
 * @author guohao
 * @date 2015年5月5日 下午2:03:59 
 *
 */

@Configuration
@ImportResource({ "classpath:META-INF/applicationContext-web.xml" })
class WebMvcConfig extends WebMvcConfigurationSupport {

	private static final String MESSAGE_SOURCE = "/WEB-INF/i18n/messages";

	private static final String RESOURCES_HANDLER = ResourceFacade.RES_PREFIX_SYS + "/**";

	/*@Autowired
	TemplateResolver templateResolver;

	@Autowired
	ResourceFacade resourceFacade;*/

//	@Value("${max.page.size}")
//	Integer maxPageSize = 50;
//
//	@Value("${message.source.cache.seconds}")
//	int msgSrcCacheSeconds =2000080;

	
	@Override
	public RequestMappingHandlerMapping requestMappingHandlerMapping() {
		RequestMappingHandlerMapping requestMappingHandlerMapping = super.requestMappingHandlerMapping();
		requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
		requestMappingHandlerMapping.setUseTrailingSlashMatch(false);
		return requestMappingHandlerMapping;
	}
	
	
   
	
	//验证消息
	@Bean(name = "messageSource")
	public MessageSource messageSource() {
		ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
		messageSource.setBasename(MESSAGE_SOURCE);
		//messageSource.setCacheSeconds(msgSrcCacheSeconds);
		messageSource.setUseCodeAsDefaultMessage(true);
		messageSource.setFallbackToSystemLocale(false);
		return messageSource;
	}
	
	/**
	 * 模板引擎
	 * @param 
	 * @author guohao
	 * @date 2015年5月5日 下午5:45:13
	 */
	@Bean
	public SpringTemplateEngine templateEngine() {
		SpringTemplateEngine templateEngine = new SpringTemplateEngine();
		//模板引擎用户的是thymeleaf
		//templateEngine.setTemplateResolver(templateResolver);
		templateEngine.addDialect(new SpringSecurityDialect());
		templateEngine.addDialect(new LayoutDialect());
	
		return templateEngine;
	}

	@Bean
	public ThymeleafViewResolver viewResolver() {
		ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
		thymeleafViewResolver.setTemplateEngine(templateEngine());
		thymeleafViewResolver.setCharacterEncoding("UTF-8");
		return thymeleafViewResolver;
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler(RESOURCES_HANDLER).addResourceLocations(ResourceFacade.RES_PREFIX_SYS);
	}

	
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}

	/**
	 * 分页参数处理
	 * @param 
	 * @author guohao
	 * @date 2015年5月5日 下午6:26:04
	 */
	@Override
	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
	    PageableHandlerMethodArgumentResolver resolver = new CustomPageableHandlerMethodArgumentResolver();
	 //   resolver.setMaxPageSize(maxPageSize);
	    argumentResolvers.add(0, new SetMethodProcessor());
	    argumentResolvers.add(0,resolver);
	    argumentResolvers.add(new PayBizTypeEnumArgumentResolver());
	    
	}
	
	/**
	 * 配置跨域拦截
	 */
	@Override
	protected void addCorsMappings(CorsRegistry registry) {
		String corsMappingStr = SpringPropertiesUtil.getPropertiestValue("cors_mappings");
		String[] corsMappings = corsMappingStr.split(",");
		 registry.addMapping("/**")
		 .allowedOrigins(corsMappings);
	};
	
	/**
	 * 增加过滤器
	 *
	 */
	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
		// TODO Auto-generated method stub
		super.addInterceptors(registry);
		registry.addInterceptor(new LogUtilInterceptor());
	}
	
	@Override
	
	public  RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
		RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter();
		StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));		
		
		List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
		supportedMediaTypes.add(MediaType.parseMediaType("application/json;charset=UTF-8"));
		supportedMediaTypes.add(MediaType.parseMediaType("text/html;charset=UTF-8"));
		supportedMediaTypes.add(MediaType.parseMediaType("application/javascript;charset=UTF-8"));
		converter.setSupportedMediaTypes(supportedMediaTypes);
		converter.setWriteAcceptCharset(false);
		List<HttpMessageConverter<?>> converters = getMessageConverters();
	    converters.add(0,converter);
	    adapter.setMessageConverters(converters);
	    /*GlobalBinding globalBinding = new GlobalBinding();
	    HashMap<String, PropertyEditor> map = new HashMap<String, PropertyEditor>();
	    map.put("java.util.Date", new DateEditor());
	    globalBinding.setPropertyEditorMap(map);
	    adapter.setWebBindingInitializer(globalBinding);*/
	    return adapter;
		 
	}
	
	@Override
	protected Validator getValidator() {
		
		OptionalValidatorFactoryBean validator = new OptionalValidatorFactoryBean();
		validator.setValidationMessageSource(messageSource());
		return validator;
	}
}
